<?php

  /*

      TravianWAP
      Copyright (c) 2007-08 by Ananas - All rights reserved
      http://n00bz.biz/travianwap/
      Contact: uroskn@gmail.com

      --------------------------------------------------------------------------

      This program is free software: you can redistribute it and/or modify
      it under the terms of the GNU  General Public License as published by
      the Free Software Foundation, either version 3 of the License, or
      (at your option) any later version.

      This program is distributed in the hope that it will be useful,
      but WITHOUT ANY WARRANTY; without even the implied warranty of
      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      GNU General Public License for more details.

      You should have received a copy of the GNU  General Public License
      along with this program. If not, see http://www.gnu.org/licenses/.

  */

  global $text, $req;
  
  echo "<strong>Marketplace</strong><br/>\n";
  $sar = array(
    array("send"  => "Send"),
    array("trade" => "Trade"),
    array("bid"   => "Bid"),
    array("atran" => "Transports")
  );

  if (empty($req["submod"])) $submod = "send";
  else $submod = $req["submod"];

  if (!$requested_gid)
  {
    $first = "";
    foreach ($sar as $key => $value)
    {
      foreach ($value as $key => $val)
      {
        if ($key != $submod)
        {
          echo "$first";
          print_link("main.php?mod=details_build&amp;id={$req["id"]}&amp;submod=$key".ps(), $val);
          $first = " - ";
        }
      }
    }
    echo "<br/>";
  }

  if ($submod == "atran")
  {
    $info = travian_return_transports($text, 0, True);
    $info = $info["transport"];
    //print_r($info);
    if (count($info) == 0) echo "<strong>No merchants on route</strong><br/>";
    for ($i = 0; $i < count($info); $i++)
    {
      if (empty($info[$i]["player"])) continue;
      echo "{$info[$i]["player"]["name"]} || {$info[$i]["village"]["name"]}<br/>".pdate($info[$i]["time"]).
           " - ".pdate($info[$i]["at"], False)."<br/>".implode(" ", $info[$i]["resources"])." ";
      if ($info[$i]["return"]) echo "[R]";
      echo "<br/><br/>";
    }
  }

  if ($submod == "send")
  {
    $send = false; $ssend = False;
    if (!empty($req["trade"]))
    {
      $resources = array(
        process_number($req["wood"]),
        process_number($req["clay"]),
        process_number($req["iron"]),
        process_number($req["crop"])
      );
      if (!$requested_gid) $infos = travian_send_resources($_SESSION, $req["id"], $resources, explode("/", $req["xy"]), $req["vname"], True);
      else
      {
        $infos = travian_send_resources($_SESSION, $req["id"], $resources, explode("/", $req["xy"]), $req["vname"], True, True);
        $req["id"] = $infos["id"];
      }
      if (!empty($info["error"])) $error = $info["error"];
      else
      {
        $send = True;
        $ssend = True;
      }
    }
    if (!empty($req["tradec"]))
    {
      $resources = array($req["r1"], $req["r2"], $req["r3"], $req["r4"]);
      travian_send_resources($_SESSION, $req["id"], $resources, explode("/", $req["xy"]), $req["vname"]);
      $text = http_get("http://{$_SESSION["serv"]}/build.php?id={$req["id"]}");
      $text = $text["body"];
    }
    $info = travian_return_transports($text, 0, True);
    $capacity = $info["merchants"][0] * $info["merchants"][2];
    $used = $info["merchants"][1] * $info["merchants"][2];
    $free = $capacity - $used;
    if (empty($info["merchants"][1]))
    {
      $error = "No merchants currently available";
      $send = True;
      $ssend = False;
    }
    if (!empty($error)) echo "$error<br/><br/>";
    if (($ssend) && (!empty($infos["error"])))
    {
      $ssend = False;
      $send = False;
      echo "{$infos["error"]}<br/><br/>";
    }
    echo "Merchants: {$info["merchants"][1]}/{$info["merchants"][0]} [{$info["merchants"][2]}]".
         "<br/>$used/$capacity [$free]<br/><br/>";
    if (!$send)
    {
      $pfields = array(
        "wood"   => '$(wood)',
        "clay"   => '$(clay)',
        "iron"   => '$(iron)',
        "crop"   => '$(crop)',
        "xy"     => '$(xy)',
        "vname"  => '$(vname)',
        "id"     => $req["id"],
        "mod"    => "details_build",
        "submod" => "send",
        "trade"  => "trade"
      );
      print_form_top("main.php".ps('?'), $pfields, "get");
      ?>Wood:<br/><input name="wood" type="text" value="0"/><br/>
        Clay:<br/><input name="clay" type="text" value="0"/><br/>
        Iron:<br/><input name="iron" type="text" value="0"/><br/>
        Crop:<br/><input name="crop" type="text" value="0"/><br/>
        X/Y coordinates:<br/><input name="xy" type="text" value="0/0"/><br/>
        Village name:<br/><input name="vname" type="text" value=""/><br/>
      <?php
      print_form_bottom("Send");
    }
    if ($ssend)
    {
      echo implode(" ", $infos["resources"])."<br/>Time: ".pdate($infos["time"])."<br/>".
           "Player: ".$infos["player"]["name"]."<br/>Village: ".$infos["vname"]."<br/>".
           "Merchants: ".$infos["merchants"]."<br/>";
      print_link("main.php?mod=details_build&amp;id={$req["id"]}&amp;submod=send&amp;".
                 "r1={$infos["resources"][0]}&amp;r2={$infos["resources"][1]}&amp;".
                 "r3={$infos["resources"][2]}&amp;r4={$infos["resources"][3]}&amp;".
                 "xy=".implode("/", $infos["coord"])."&amp;vname={$infos["vname"]}&amp;".
                 "tradec=1".ps(), "Send resources<br/><br/>");
    }
  }

  if ($submod == "trade")
  {
    if (empty($req["page"])) $page = 0;
    else $page = $req["page"];
    $info = travian_return_trade_info($_SESSION, $req["id"], $page);
    for ($i = 1; $i < count($info) - 25; $i++)
    {
      if (($info[$i]["cando"]) && (is_numeric($info[$i]["offer"]["count"])))
      {
        print_link("main.php?mod=direct_call&amp;file=build&amp;".htmlspecialchars($info[$i]["link"])."&amp;return=details_build&amp;submod=trade&amp;page={$req["page"]}".ps(), "Trade");
        echo " {$info[$i]["owner"]["name"]}<br/>";
        switch ($info[$i]["offer"]["type"])
        {
          case 1: echo "WO"; break;
          case 2: echo "CL"; break;
          case 3: echo "IR"; break;
          case 4: echo "CR"; break;
        }
        echo " {$info[$i]["offer"]["count"]}/";
        switch ($info[$i]["demand"]["type"])
        {
          case 1: echo "WO"; break;
          case 2: echo "CL"; break;
          case 3: echo "IR"; break;
          case 4: echo "CR"; break;
        }
        $temp = pdate($info[$i]["time"]);
        echo " {$info[$i]["demand"]["count"]}<br/>$temp<br/><br/>";
      }
    }
    $b = $page - 1; $f = $page + 1;
    if ($page != 0) echo print_link("main.php?mod=details_build&amp;id={$req["id"]}&amp;submod=trade&amp;page=$b".ps(), "Back", " - ");
    echo print_link("main.php?mod=details_build&amp;id={$req["id"]}&amp;submod=trade&amp;page=$f".ps(), "Foward", "<br/><br/>");
  }

  if ($submod == "bid")
  {
    if (!empty($req["trade"]))
    {
      $time_bool = "1";
      if ($req["time"] == "-1") $time_bool = "";
      $form = array(
        "id"   => $req["id"],
        "a"    => "4",
        "t"    => "2",
        "rid1" => $req["offer_type"],
        "rid2" => $req["demand_type"],
        "m1"   => process_number($req["offer"]),
        "m2"   => process_number($req["demand"]),
        "ally" => "",
        "d1"   => $time_bool,
        "d2"   => $req["time"]
      );
     $text = http_post("http://{$_SESSION["serv"]}/build.php", $form);
     $text = $text["body"];
    }
    $info = travian_return_bid_info($_SESSION, $req["id"]);
    echo "Merchants: {$info["mer"][0]}/{$info["mer"][1]}<br/><br/>";
    $pfields = array(
      "offer"        => '$(offer)',
      "offer_type"   => '$(offer_type)',
      "demand"       => '$(demand)',
      "demand_type"  => '$(demand_type)',
      "time"         => '$(time)',
      "mod"          => 'details_build',
      "id"           => $req["id"],
      "submod"       => "bid",
      "trade"        => '1'
    );
    print_form_top("main.php".ps('?'), $pfields, "get");
    ?>Offer:<br/><input name="offer" type="text" value="0"/><br/>
    <select name="offer_type">
      <option value="1">Wood</option><option value="2">Clay</option>
      <option value="3">Iron</option><option value="4">Crop</option>
    </select><br/><br/>
    Demand:<br/><input name="demand" type="text" value="0"/><br/>
    <select name="demand_type">
      <option value="1">Wood</option><option value="2">Clay</option>
      <option value="3">Iron</option><option value="4">Crop</option>
    </select><br/><br/>
    Time limit (-1 = none):<br/><input name="time" type="text" value="-1"/><br/>
    <?php
    print_form_bottom("Bid");
    if ($info["bids"]["count"] != -1)
    {
      echo "<strong>Active offers</strong><br/>";
      for ($i = 0; $i < count($info["bids"]); $i++)
      {
        print_link("main.php?mod=direct_call&amp;file=build&amp;".htmlspecialchars($info["bids"][$i]["url"])."&amp;return=details_build&amp;submod=bid".ps(), "X", " ");
        switch ($info["bids"][$i]["offer"]["type"])
        {
          case 1: echo "WO"; break;
          case 2: echo "CL"; break;
          case 3: echo "IR"; break;
          case 4: echo "CR"; break;
        }
        echo " {$info["bids"][$i]["offer"]["count"]}/";
        switch ($info["bids"][$i]["demand"]["type"])
        {
          case 1: echo "WO"; break;
          case 2: echo "CL"; break;
          case 3: echo "IR"; break;
          case 4: echo "CR"; break;
        }
        echo " {$info["bids"][$i]["demand"]["count"]}<br/>";
      }
      echo "<br/>";
    }
  }

  if (!$requested_gid) print_link("main.php?mod=construct&amp;id={$req["id"]}".ps(), "Back", "<br/>");

